import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:nmb/models/fold.dart';
import 'package:nmb/utils/util.dart';
import '../services/global.dart';

class SelectFold extends Fold{
  SelectFold({required super.id, required super.name});

  bool select = false;


}

class FolderManage extends StatefulWidget {
  const FolderManage({super.key});
  @override
  State<FolderManage> createState() => _FolderManageState();
}

class _FolderManageState extends State<FolderManage> {


  late List<SelectFold> foldList;

  final service = Get.find<GlobalService>();

  final ValueNotifier<bool> selectMode = ValueNotifier(false);

  @override
  void initState() {
    super.initState();
    loadFold();
    service.folderChanged.addListener((){
      loadFold();
    });
  }

  loadFold(){
    foldList = service.foldList.map((f){
      return SelectFold(id: f.id, name: f.name);
    }).toList();
  }

  addFold(){
    final ctl = TextEditingController();
    showModalBottomSheet(
      context: context,
      backgroundColor: Color(0xff242424),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      isScrollControlled: true, // Allows the sheet to expand
      builder: (BuildContext context) {
        return SingleChildScrollView(
          child: Container(
            padding: EdgeInsets.only(
              bottom: MediaQuery.of(context).viewInsets.bottom,
            ),
            margin: EdgeInsets.symmetric(horizontal: 16),
            child: Container(
              padding: EdgeInsets.all(16.0),
              child: Column(
                children: [
                  Text('新建文件夹',style: TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold
                  ),),
                  SizedBox(
                    height: 16,
                  ),
                  Container(
                      decoration: BoxDecoration(
                        color: Colors.black,borderRadius: BorderRadius.circular(32),
                      ),
                      padding: EdgeInsets.symmetric(horizontal: 16),
                      child: TextField(
                        controller: ctl,
                        cursorColor: Colors.amber,
                          style: TextStyle(
                            color: Colors.white
                          ),
                          decoration: InputDecoration(hintText: '输入文件夹名称',border: InputBorder.none))),
                  SizedBox(
                    height: 16,
                  ),
                  GestureDetector(
                    onTap: () async {
                      final fd = Fold(id: Util.uuid(), name: ctl.text);
                      await service.addFold(fd);
                      Get.back();
                    },
                    child: FractionallySizedBox(
                      widthFactor: 1,
                      child: Container(
                        decoration: BoxDecoration(
                          color: Colors.amber,
                          borderRadius: BorderRadius.circular(32)
                        ),
                        padding: EdgeInsets.symmetric(horizontal: 8,vertical: 8),
                        child: Center(
                          child: Text('确定',style: TextStyle(
                            color: Colors.white,
                            fontSize: 18,
                            fontWeight: FontWeight.bold
                          ),),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 16,
                  )
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  editFold(Fold fd){
    final ctl = TextEditingController();
    ctl.text = fd.name;
    showModalBottomSheet(
      context: context,
      backgroundColor: Color(0xff242424),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      isScrollControlled: true, // Allows the sheet to expand
      builder: (BuildContext context) {
        return SingleChildScrollView(
          child: Container(
            padding: EdgeInsets.only(
              bottom: MediaQuery.of(context).viewInsets.bottom,
            ),
            margin: EdgeInsets.symmetric(horizontal: 16),
            child: Container(
              padding: EdgeInsets.all(16.0),
              child: Column(
                children: [
                  Text('新建文件夹',style: TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                      fontWeight: FontWeight.bold
                  ),),
                  SizedBox(
                    height: 16,
                  ),
                  Container(
                      decoration: BoxDecoration(
                        color: Colors.black,borderRadius: BorderRadius.circular(32),
                      ),
                      padding: EdgeInsets.symmetric(horizontal: 16),
                      child: TextField(
                          controller: ctl,
                          cursorColor: Colors.amber,
                          style: TextStyle(
                              color: Colors.white
                          ),
                          decoration: InputDecoration(hintText: '输入文件夹名称',border: InputBorder.none))),
                  SizedBox(
                    height: 16,
                  ),
                  GestureDetector(
                    onTap: () async {
                      await service.updateFold(Fold(id: fd.id, name: ctl.text));
                      Get.back();
                    },
                    child: FractionallySizedBox(
                      widthFactor: 1,
                      child: Container(
                        decoration: BoxDecoration(
                            color: Colors.amber,
                            borderRadius: BorderRadius.circular(32)
                        ),
                        padding: EdgeInsets.symmetric(horizontal: 8,vertical: 8),
                        child: Center(
                          child: Text('确定',style: TextStyle(
                              color: Colors.white,
                              fontSize: 18,
                              fontWeight: FontWeight.bold
                          ),),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 16,
                  )
                ],
              ),
            ),
          ),
        );
      },
    );
  }


  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: selectMode,
      builder: (BuildContext context, select, Widget? child) {
        return Scaffold(
          appBar: AppBar(
            title: Text('文件夹'),
            centerTitle: true,
            backgroundColor: Color(0xff242424),
            foregroundColor: Colors.white,
            actions: [
              if (select) IconButton(onPressed: (){
                        selectMode.value = !selectMode.value;
                        Get.snackbar('提示', '仅删除文件夹，文件夹下的笔记归类到【全部】');
                        final selectedIds = foldList.where((e)=>e.select).map((e)=>e.id).toList();
                        service.delFold(selectedIds);

              }, icon: Icon(Icons.check)) else IconButton(onPressed: (){
                         selectMode.value = !selectMode.value;
              }, icon: Icon(Icons.delete_rounded))
            ],
          ),
          backgroundColor: Color(0xff242424),
          body: ListenableBuilder(
            listenable: service.folderChanged,
            builder: (BuildContext context, Widget? child) {
              return CustomScrollView(
                slivers: [
                  SliverList.builder(
                      itemCount: foldList.length,
                      itemBuilder: (context,index){
                        final fd = foldList[index];
                        return GestureDetector(
                          onLongPress: (){
                            editFold(fd);
                          },
                          onTap: (){
                            if(!select) return;
                            if(fd.id.isEmpty) return;
                            setState(() {
                              fd.select = !fd.select;
                            });
                          },
                          child: Container(
                            margin: EdgeInsets.only(left: 16.0,right: 16,bottom: 16),
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(16.0),
                                color: Color(0xff343434)
                            ),
                            child: ListTile(
                              title: Text(fd.name,style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 18
                              ),),
                              trailing: fd.select ? Icon(Icons.check,color: Colors.amber,):SizedBox()
                            ),
                          ),
                        );
                      }),
                  SliverToBoxAdapter(
                    child: GestureDetector(
                      onTap: (){
                        addFold();
                      },
                      child: Container(
                        margin: EdgeInsets.symmetric(horizontal: 16.0),
                        padding: EdgeInsets.symmetric(vertical: 8),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(16.0),
                            color: Color(0xff343434)
                        ),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Container(
                              padding: EdgeInsets.all(2.0),
                              decoration: BoxDecoration(
                                  color: Colors.amber,
                                  borderRadius: BorderRadius.circular(32)
                              ),
                              child: Icon(Icons.add,color: Colors.white,),
                            ),
                            Text('新建文件夹',style: TextStyle(
                                color: Color(0xffdddddd)
                            ),),
                          ],
                        ),
                      ),
                    ),
                  )
                ],
              );
            },
          ),
        );
      },

    );
  }
}
